<template>
  <video-player 
    v-if="hasDetail"
    class="vp" 
    :url="playUrl" 
    :poster="detailData.pic" 
    :duration="detailData.duration"
  ></video-player>
  <van-tabs 
    v-if="hasDetail" 
    class="tabs" 
    v-model:active="activeTab" 
    :title-active-color="themeColor"
    @change="handleTabChange"
  >
    <van-tab title="简介">
      <video-info :detail-data="detailData" :tags="videoTags"></video-info>
      <video-toolbar :detail-data="detailData"></video-toolbar>
      <video-episode :detail-data="detailData" @select="handleEpisode"></video-episode>
      <video-related :videos="relatedVideos"></video-related>                        
    </van-tab>
    <van-tab>
      <template #title>评论 {{commentNum}}</template>
      <video-comment 
        :comments="videoComments"
      ></video-comment>
    </van-tab>
  </van-tabs>
</template>

<script>
import { inject, reactive, computed, toRefs, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Tabs as VanTabs, Tab as VanTab } from 'vant'
import VideoPlayer from '@/components/VideoPlayer'
import VideoInfo from './info'
import VideoToolbar from './toolbar'
import VideoEpisode from './episode'
import VideoRelated from './related'
import VideoComment from '@/components/Comment'
import { videoApi } from '@/api'
import { formatNumber } from '@/utils'
export default {
  name: 'Video',
  components: {
    VanTabs,
    VanTab,
    VideoPlayer,
    VideoInfo,
    VideoToolbar,
    VideoEpisode,
    VideoRelated,
    VideoComment
  },
  props: {
    bvid: {
      type: String
    }
  },
  setup(props) {
    const router = useRouter()
    const params = reactive({
      detailData: null,
      commentNum: '',
      playUrl: '',
      activeTab: 0,
      themeColor: inject('themeColor'),      
      hasDetail: computed(() => !!params.detailData)
    })
    const videoTags = reactive([])
    const relatedVideos = reactive([])
    const videoComments = reactive([])
    
    // 初始化数据
    const initData = async () => {
        try {
            await getData()           
            const redirectUrl = params.detailData.redirect_url
            if (typeof redirectUrl !== 'undefined') {
                // 跳转番剧详细页
                const id = redirectUrl.substring(redirectUrl.lastIndexOf('/') + 1)
                router.push({
                  name: 'bangumi',
                  params: {
                    id
                  }
                })
            } else if(params.hasDetail) {
                await Promise.all([
                  getPlayUrl(),
                  getVideoTags(),
                  getVideoRelated()
                ])  
            }                   
        } catch (error) { 
          console.log(error)
          router.push({
            name: '404'
          })
        }
    }

    // 获取视频详细信息
    const getData = async () => {
      try { 
        const { data } = await videoApi.getVideo({
          bvid: props.bvid
        })
        params.detailData = data
        params.commentNum = formatNumber(data.stat.reply)
      } catch (error) {
        console.log(error)
        throw new Error(error)
      }        
    }

     // 获取播放地址
    const getPlayUrl = async ({ aid, bvid, cid } = {}) => {
      try {
        if (!aid && !bvid && !cid) {
          aid = params.detailData.aid
          bvid = params.detailData.bvid
          cid = params.detailData.cid
        }
        const { data } = await videoApi.getPlayUrl({
          avid: aid,
          bvid,
          cid
        })
        if (!data) {
            return
        }
        const { durl } = data
        params.playUrl = durl[0].url        
      } catch (error) {
        console.log(error)
      }
    }

    // 获取视频标签
    const getVideoTags = async () => {
      try {
        const { aid, bvid } = params.detailData
        const { data } = await videoApi.getVideoTags({
          aid,
          bvid
        })
        if (!data) {
          return
        }
        videoTags.splice(0, videoTags.length)
        videoTags.push(...data)        
      } catch (error) {   
        console.log(error)         
      }
    }

    // 获取相关视频
    const getVideoRelated = async () => {
      try {
        const { aid, bvid } = params.detailData
        const { data } = await videoApi.getVideoRelated({
            aid,
            bvid
        })
        if (!data) {
            return
        }
        relatedVideos.splice(0, relatedVideos.length)
        relatedVideos.push(...data.slice(0, 40))
      } catch (error) {      
        console.log(error)      
      }
    }

    // 获取视频评论
    const getVideoComments = async () => {
      try {
        const { aid, bvid } = params.detailData
        const { data } = await videoApi.getVideoComments({
          oid: aid,
          bvid
        })
        if (!Array.isArray(data.replies)) {
            return
        } 
        videoComments.splice(0, videoComments.length)
        videoComments.push(...data.replies)                   
      } catch (error) {        
        console.log(error)    
      }
    }

    const handleEpisode = episode => {
        getPlayUrl({
          aid: params.detailData.aid,
          bvid: params.detailData.bvid,
          cid: episode.cid
        })
    }

    const handleTabChange = (name) => {
      if (name === 1 && !videoComments.length) {
        // 评论标签首次加载
        getVideoComments()
      }
    }

    initData()
    watch(() => props.bvid, () => {
      initData()
    })

    return {
      ...toRefs(params),
      videoTags,
      relatedVideos,
      videoComments,
      handleEpisode,
      handleTabChange
    }

  }
}
</script>

<style lang="scss" scoped>
  @media screen and (orientation:portrait) {
    // 竖屏
    .vp{
      position: sticky;
      top: 44px;
      z-index: 2;
    }
    .tabs :deep .van-tabs__wrap {
      position: sticky;
      top: 255px;
      z-index: 2;
    }
  }
</style>